package com.db.manage.service;

import com.db.manage.config.DriverConfig;
import com.db.manage.exception.DriverException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
@RequiredArgsConstructor
public class DriverService {
    private final DriverConfig driverConfig;

    public void uploadDriver(MultipartFile file, String dbType, String version) throws IOException {
        // 验证文件类型
        if (!isValidFileType(file.getContentType())) {
            throw new DriverException("不支持的文件类型");
        }

        // 验证文件大小
        if (file.getSize() > driverConfig.getMaxFileSize()) {
            throw new DriverException("文件大小超过限制");
        }

        // 创建存储目录
        String storagePath = Paths.get(driverConfig.getStoragePath(), dbType, version).toString();
        Files.createDirectories(Paths.get(storagePath));

        // 保存文件
        String fileName = file.getOriginalFilename();
        Path targetPath = Paths.get(storagePath, fileName);
        Files.copy(file.getInputStream(), targetPath);
    }

    public void downloadDriver(String dbType, String version, String driverName) throws IOException {
        String driverPath = Paths.get(driverConfig.getStoragePath(), dbType, version, driverName).toString();
        File driverFile = new File(driverPath);
        
        if (!driverFile.exists()) {
            // 从Maven中央仓库下载
            String mavenUrl = buildMavenUrl(dbType, version, driverName);
            downloadFromMaven(mavenUrl, driverPath);
        }
    }

    private boolean isValidFileType(String contentType) {
        for (String allowedType : driverConfig.getAllowedTypes()) {
            if (allowedType.equals(contentType)) {
                return true;
            }
        }
        return false;
    }

    private String buildMavenUrl(String dbType, String version, String driverName) {
        // 根据数据库类型构建Maven仓库URL
        switch (dbType.toLowerCase()) {
            case "mysql":
                return String.format("https://repo1.maven.org/maven2/mysql/mysql-connector-java/%s/mysql-connector-java-%s.jar",
                        version, version);
            case "oracle":
                return String.format("https://repo1.maven.org/maven2/com/oracle/database/jdbc/ojdbc8/%s/ojdbc8-%s.jar",
                        version, version);
            default:
                throw new DriverException("不支持的数据库类型");
        }
    }

    private void downloadFromMaven(String url, String targetPath) throws IOException {
        try {
            URL mavenUrl = new URL(url);
            Files.copy(mavenUrl.openStream(), Paths.get(targetPath));
        } catch (IOException e) {
            throw new DriverException("从Maven仓库下载驱动失败: " + e.getMessage());
        }
    }
} 